package com.secondkill.messagequeue.rabbitmq;

import com.secondkill.entity.MiaoshaOrder;
import com.secondkill.entity.MiaoshaUser;
import com.secondkill.entity.OrderInfo;
import com.secondkill.redis.RedisService;
import com.secondkill.service.MiaoshaGoodsService;
import com.secondkill.service.MiaoshaService;
import com.secondkill.service.OrderService;
import com.secondkill.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * Created by zhangkai12 on 2018/7/6.
 */
@Service
public class RabbitMqReceiver {
    @Autowired
    MiaoshaGoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    MiaoshaService miaoshaService;
    private Logger logger = LoggerFactory.getLogger(RabbitMqReceiver.class);
    @RabbitListener(queues = "someQueue")
    public void processMessage(String content) {
        System.out.println("consumer content " + content);
    }

    @RabbitListener(queues = "topic.queue1")
    public void processTopicExchange1(String content) {
        logger.info("receiver topic queue1 data: {}", content);
    }


    @RabbitListener(queues = "topic.queue2")
    public void processTopicExchange2(String content) {
        logger.info("receiver topic queue2 data: {}", content);
    }

    @RabbitListener(queues = "miaosha.queue")
    public void processMiaoSha(String mm) {

        System.out.println("处理秒杀队列");
        MiaoshaMessage miaoshaMessage = RedisService.stringToT(mm, MiaoshaMessage.class);
        if (mm == null) {
            return;
        }
        final MiaoshaUser miaoshaUser = miaoshaMessage.getMiaoshaUser();
        long goodsId = miaoshaMessage.getGoodsId();
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        int stock = goods.getStockCount();
        if(stock <= 0) {
            return;
        }
        //判断是否已经秒杀到了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(miaoshaUser.getId(), goodsId);
        if(order != null) {
            return;
        }
        //减库存 下订单 写入秒杀订单
        miaoshaService.miaosha(miaoshaUser, goods);

    }
}
